package collect

import (
	"fmt"
	"sync"

	"gitee.com/xuesongtao/collect/library"
	pslog "gitee.com/xuesongtao/ps-log"
	"github.com/gogf/gf/os/glog"
)

type ToFeiShu struct {
	cli     *library.HttpCli `json:"-"`
	mu      sync.Mutex       `json:"-"`
	WebHook string           `json:"web_hook"`
	At      []AtInfo         `json:"at"`
}

type AtInfo struct {
	OpenId string `json:"open_id"`
	Name   string `json:"name"`
}

func (t *ToFeiShu) Init() {
	t.cli = library.NewHttpCli()
}

func (t *ToFeiShu) WriteTo(bus *pslog.LogHandlerBus) {
	glog.Info("push feishu")
	t.PushText(&PushParam{
		Title:   ParsePushLogTitle(bus),
		Content: bus.Msg,
	})
}

// API: https://open.larksuite.com/document/client-docs/bot-v3/use-custom-bots-in-a-group

func (t *ToFeiShu) PushText(param *PushParam) (*library.HttpCliResp, error) {
	at := ""
	for _, info := range t.At {
		at += fmt.Sprintf("<at user_id=\"%v\"></at>", info.OpenId)
	}
	if at == "" {
		at = fmt.Sprintf("<at user_id=\"%v\"></at>", "all")
	}

	glog.Infof("push content: %q", param.Content)
	text := at + "\n" +
		param.Title + "\n" +
		param.Content + "\n"

	// 将 appName 通过 fmt 替换
	val := library.NewBodyMap(3).Set("text", text)
	req := library.NewBodyMap(3)
	req.Set("msg_type", TextForReq).
		Set("content", val.UnEscape())
	return t.push(req)
}

func (t *ToFeiShu) push(req library.BodyMap) (*library.HttpCliResp, error) {
	body, err := req.Marshal()
	if err != nil {
		return nil, err
	}
	// 保证推送是串行
	t.mu.Lock()
	defer t.mu.Unlock()
	return t.cli.Post(t.WebHook, body)
}
